﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Razor;
using System;

namespace Pear.Web.Core
{
    /// <summary>
    /// MVC页面基类
    /// </summary>
    /// <typeparam name="TModel"></typeparam>
    public abstract class PearRazorPage<TModel> : RazorPage<TModel>
    {

        #region "获取传值"
        /// <summary>
        /// 获取System.Web.HttpRequest.QueryString、System.Web.HttpRequest.Form
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Name"></param>
        /// <param name="errorReturn"></param>
        /// <param name="IsLostHTML"></param>
        /// <returns></returns>
        public T GetValue<T>(string Name, T errorReturn, bool IsLostHTML = true)
        {
            return GetValue<T>(ViewContext.HttpContext.Request,Name, errorReturn);
        }

        /// <summary>
        /// 获取System.Web.HttpRequest.QueryString、System.Web.HttpRequest.Form
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="errorReturn"></param>
        /// <param name="IsLostHTML"></param>
        /// <returns></returns>
        public string GetValue(string Name, string errorReturn, bool IsLostHTML = true)
        {
            return GetValue<string>(ViewContext.HttpContext.Request, Name, errorReturn);
        }

        /// <summary>
        /// 获取GET/POST传值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <param name="Name"></param>
        /// <param name="errorReturn"></param>
        /// <returns></returns>
        public static T GetValue<T>(HttpRequest request, string Name, T errorReturn)
        {

            try
            {
                string retStr = Convert.ToString(errorReturn);
                if (request.Query.ContainsKey(Name))
                {
                    retStr = request.Query[Name];
                }
                else if (request.Form.ContainsKey(Name))
                {
                    retStr = request.Form[Name];

                }
                errorReturn = (T)Convert.ChangeType(retStr, typeof(T));
            }
            catch
            {
                return errorReturn;
            }
            return errorReturn;
        }


        #endregion

    }
}
